﻿#include "stm32regs.h"
#include "stm32regbit.h"
#include "stm32_usart.h"
#include "stm32_gpio.h"
#include "multi_timer.h"
extern void SystemClock_Config(void);
/*
 * main.c
 *
 *  Created on: 2020-12-12
 *      Author: pengdan
 */
int xx = 0xfffff;
int yy = 0;
int zz = 0x33;
int status = 0;
uint32_t _ticks = 0;

struct Timer timer1;

void led_config(void)
{
	u32 tmpreg;
	//设置时钟
	/* Delay after an RCC peripheral clock enabling */
	SET_BIT(RCC->AHB2ENR, RCC_AHB2SMENR_GPIOASMEN_Msk);
	tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2SMENR_GPIOASMEN_Msk);
	(void)(tmpreg);
	WRITE_REG(GPIOA->BRR, GPIO_BSRR_BS5);

/* Initialize  pinpos on first pin set */
//pinpos = POSITION_VAL(GPIO_BSRR_BS5);
#if 1
	//设置模式
	/*MODIFY_REG(GPIOA->MODER, (GPIO_MODER_MODE0 << (POSITION_VAL(GPIO_BSRR_BS5) * 2U)),\
						 (GPIO_MODER_MODE0_0 << (POSITION_VAL(GPIO_BSRR_BS5) * 2U))); */
	GPIOA->MODER &= ~(3 << GPIO_BSRR_BS5_Pos * 2U);
	GPIOA->MODER |= (1 << GPIO_BSRR_BS5_Pos * 2U);
	//设置速度
	/*MODIFY_REG(GPIOA->OSPEEDR, (GPIO_OSPEEDR_OSPEED0 << (POSITION_VAL(GPIO_BSRR_BS5) * 2U)),\
						 (GPIO_OSPEEDR_OSPEED0_0 << (POSITION_VAL(GPIO_BSRR_BS5) * 2U)));*/
	GPIOA->OSPEEDR &= ~(3 << GPIO_BSRR_BS5_Pos * 2U);
	GPIOA->OSPEEDR |= (0 << GPIO_BSRR_BS5_Pos * 2U);
	//设置上下拉
	/*MODIFY_REG(GPIOA->PUPDR, (GPIO_PUPDR_PUPD0 << (POSITION_VAL(GPIO_BSRR_BS5) * 2U)),\
						 (0 << (POSITION_VAL(GPIO_BSRR_BS5) * 2U)));*/
	GPIOA->PUPDR &= ~(3 << GPIO_BSRR_BS5_Pos * 2U);
	GPIOA->PUPDR |= (0 << GPIO_BSRR_BS5_Pos * 2U);
	//设置输出模式  推挽
	MODIFY_REG(GPIOA->OTYPER, GPIO_BSRR_BS5, (GPIO_BSRR_BS5 * 0));

	WRITE_REG(GPIOA->BSRR, GPIO_BSRR_BS5);
#endif
}

void led_control(u8 status)
{
	if (status)
	{
		WRITE_REG(GPIOA->BSRR, GPIO_BSRR_BS5);
	}

	else
	{
		WRITE_REG(GPIOA->BRR, GPIO_BSRR_BS5);
	}
}

extern void System_mDelay(uint32_t Delay);
extern void GPIO_SET(GPIO_TypeDef *GPIOx, uint32_t pin, u8 status);
void timer1_callback()
{
	if (status)
	{
		led_control(1);
		//GPIO_SET(GPIOC, 4, 1);

		status = 0;
	}
	else
	{
		led_control(0);
		//GPIO_SET(GPIOC, 4, 0);
		status = 1;
		//mywrite(zz);
	}
}

int main(void)
{
	u8 data[100];
	u16 length;
	SystemClock_Config();
	//led_config();
	gpio_config(GPIOA, 5);

	led_control(0);
	USART1_Config(170000000, 115200);
	timer_init(&timer1, timer1_callback, 0, 1);
	timer_start(&timer1);
	while (1)
	{
		timer_loop();
		length = USART1_ReceiveData((u8 *)&data);
		if (length)
		{
			USART1_SendData((u8 *)&data, length);
		}
	}
	return 0;
}

void SysTick_Handler(void)
{
	timer_ticks();
	USART1_TimeOutCounter();
}
